package me.xiaoyan.android.widget;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;


import android.graphics.Bitmap;

public class CardStorageManager {

	private static final String TAG = YLog.getTag(CardStorageManager.class);
	private static CardStorageManager mObj;

	private CardStorageManager() {
	}

	public static CardStorageManager getInstance() {
		return mObj != null ? mObj : new CardStorageManager();
	}

	public boolean saveString(String source, String fileName) {
		if(!AppSetting.HAS_SDCARD){
			return false;
		}
		FileOutputStream fos = null;
		OutputStreamWriter osw = null;
		boolean saveSuccess = true;
		try {
			fos = new FileOutputStream(fileName);
			osw = new OutputStreamWriter(fos);
			osw.write(source);
		} catch (IOException e) {
			YLog.e(TAG, "IOException(37)",e.toString());
			saveSuccess = false;
		}finally{
			if(null != osw){
				try {
					osw.close();
				} catch (IOException e) {
				}
			}
			if(null != fos){
				try {
					fos.close();
				} catch (IOException e) {					
				}
			}
		}
		return saveSuccess;
	}
	
	public String readString(String fileName) {
		YLog.i(TAG, fileName);
		if(!AppSetting.HAS_SDCARD){
			return null;
		}
		File f= new File(fileName);
		FileInputStream fis = null;
		String source = null;
		try {
			if(!f.exists()){
				return null;
			}
			fis = new FileInputStream(f);
			int len = fis.available();
			if (len > 0) {
				byte[] data = new byte[len];
				fis.read(data);
				source = new String(data, AppSetting.SOURCE_CHARSET);
			}
		} catch (IOException e) {
			YLog.e(TAG, e.toString());
		}finally{
			if(null != fis){
				try {
					fis.close();
				} catch (IOException e) {					
				}
			}
		}
		return source;
	}

	@SuppressWarnings("unused")
	private void saveImage(String name, Bitmap bitmap) throws IOException {
		File f = new File(name);
		if (f.exists()) {
			f.delete();
		}
		f.createNewFile();
		FileOutputStream fout = new FileOutputStream(f);
		bitmap.compress(Bitmap.CompressFormat.PNG, 100, fout);
		fout.flush();
		fout.close();
	}
}
